package com.example.excel.ui.activity.query;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.lifecycle.Observer;

import com.android.scanner.impl.ReaderManager;
import com.example.excel.R;
import com.example.excel.base.BaseActivity;
import com.example.excel.bean.InventoryBean;
import com.example.excel.broadcast.SystemBroadCast;
import com.example.excel.databinding.ActivityInventoryBinding;
import com.example.excel.db.InventoryController;
import com.example.excel.utils.Utils;

import java.util.Objects;

import per.goweii.actionbarex.common.OnActionBarChildClickListener;

public class InventoryActivity extends BaseActivity<ActivityInventoryBinding, InventoryViewModel> {

    private ReaderManager readerManager;
    private int outPutMode;
    private boolean enableScanKey;
    private boolean isActive;
    private boolean isScan;


    public static void start(Context context) {
        Intent intent = new Intent(context, InventoryActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected Class<InventoryViewModel> initViewModel() {
        return InventoryViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_inventory;
    }

    @Override
    protected void initView() {
        mBinding.setItemBean(new InventoryBean());
        mBinding.abc.setOnLeftIconClickListener(new OnActionBarChildClickListener() {
            @Override
            public void onClick(View v) {
                showFinishDialog();
            }
        });
        // Register receiver
        IntentFilter intentFilter = new IntentFilter(SystemBroadCast.SCN_CUST_ACTION_SCODE);
        registerReceiver(scanDataReceiver, intentFilter);
        readerManager = ReaderManager.getInstance();
        initScanner();

        mBinding.btnScan.setOnTouchListener(new View.OnTouchListener() {
            @SuppressLint("ClickableViewAccessibility")
            @Override
            public boolean onTouch(View v, @SuppressLint("ClickableViewAccessibility") MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    if (outPutMode != 2) {
                        readerManager.setOutPutMode(2);
                        Log.d("btnScan", "-------ScannerService-----------------setOutPutMode(2)--------");
                    }
                    readerManager.beginScanAndDeocde();
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    try {
                        Thread.sleep(150);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    readerManager.stopScanAndDecode();
                }
                return false;
            }
        });
    }

    private void showFinishDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("确定退出本次盘点吗？");
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                unInitScanner();
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                unInitScanner();
                finish();
            }
        });
        builder.show();
    }

    @Override
    protected void registerObserve() {
        super.registerObserve();
        mViewModel.mBean.observe(this, new Observer<InventoryBean>() {
            @Override
            public void onChanged(InventoryBean inventoryBean) {
                if (inventoryBean != null) {
                    inventoryBean.setFaFlag(1);
                    mBinding.setItemBean(inventoryBean);
                    mBinding.emptyLayout.setVisibility(View.GONE);
                    InventoryController.getInstance().update(inventoryBean);
                } else {
                    mBinding.emptyLayout.setVisibility(View.VISIBLE);
                    Utils.getInstance().showToast("盘点数据不存在");
                }
            }
        });
    }

    public void addOrScan() {
        String code = mBinding.etCode.getText().toString();
        if (!TextUtils.isEmpty(code)) {
            mViewModel.query(code);
        } else {
            Utils.getInstance().showToast("扫描为空");
        }
    }

    private void initScanner() {
        // 获取扫描头是否使能
        isActive = readerManager.GetActive();
        if (!isActive) {
            // 使能扫描头
            readerManager.SetActive(true);
        }
        // 打开或者关闭扫描按键
        enableScanKey = readerManager.isEnableScankey();
        if (!enableScanKey) {
            readerManager.setEnableScankey(true);
        }
        // 3。获取当前数据输出模式:0表示复制粘贴，1表示键仿真，2表示API。
        // 如果模式不是API，请将其配置为mode API，并在销毁activity时恢复到原始模式。
        outPutMode = readerManager.getOutPutMode();
        if (outPutMode != 2) {
            readerManager.setOutPutMode(2);
        }
        // 4。设置结束字符:
        // 0代码末尾添加“\n”
        // 1代码末尾添加" "
        // 2代码末尾添加“\t”
        // 3空
        readerManager.setEndCharMode(3);
        readerManager.stopScanAndDecode();
    }

    private void unInitScanner() {
        unregisterReceiver(scanDataReceiver);
        if (readerManager != null) {
            readerManager.setOutPutMode(outPutMode);
            int endCharMode = 0;
            readerManager.setEndCharMode(endCharMode);
            readerManager.setEnableScankey(enableScanKey);
            readerManager.SetActive(isActive);
            readerManager.stopScanAndDecode();
            readerManager.Release();
            readerManager = null;
        }
    }

    //The broadcast about transmit scanning data information
    private final BroadcastReceiver scanDataReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Objects.equals(intent.getAction(), SystemBroadCast.SCN_CUST_ACTION_SCODE)) {
                try {
                    String message = intent.getStringExtra(SystemBroadCast.SCN_CUST_EX_SCODE);
                    Log.d("ScanTest", "-------ScannerService----------message = " + message);
                    mBinding.etCode.setText(TextUtils.isEmpty(message) ? "" : message);
                    addOrScan();
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e("ScanTest", e.toString());
                    Utils.getInstance().showToast("e:" + e.toString());
                } finally {
                    readerManager.stopScanAndDecode();
                }
            }
        }
    };

    @Override
    public void onBackPressed() {
        showFinishDialog();
    }
}
